﻿using System.IO;
using System.Windows;
using Schedulr.Infrastructure;
using Schedulr.Models;

namespace Schedulr.ViewModels
{
    /// <summary>
    /// The view model for a picture in a picture list.
    /// </summary>
    public class PictureViewModel
    {
        /// <summary>
        /// Gets the picture.
        /// </summary>
        public Picture Picture { get; private set; }

        /// <summary>
        /// Gets the URL of the image to display in the list.
        /// </summary>
        public string ImageUrl { get; private set; }

        /// <summary>
        /// Gets a value that determines if the picture has errors.
        /// </summary>
        public bool HasErrors { get; set; }

        /// <summary>
        /// Gets a value that determines if the file is actually a video.
        /// </summary>
        public bool IsVideo { get; private set; }

        /// <summary>
        /// Gets the visibility of the title in the picture preview.
        /// </summary>
        public Visibility PreviewTitleVisibility { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="PictureViewModel"/> class.
        /// </summary>
        /// <param name="picture">The picture.</param>
        /// <param name="account">The account.</param>
        public PictureViewModel(Picture picture, Account account)
        {
            this.Picture = picture;
            this.IsVideo = App.IsVideoFile(picture.FileName);
            string imageUrl;
            var fileExists = File.Exists(picture.FileName);
            if (!fileExists && !string.IsNullOrWhiteSpace(this.Picture.PreviewUrl))
            {
                // There is an online preview URL (of the uploaded picture) and the local file
                // doesn't exist anymore so use the online preview URL.
                imageUrl = picture.PreviewUrl;
            }
            else
            {
                if (this.IsVideo)
                {
                    imageUrl = App.GetResourceUrl("/Resources/Movie.png");
                }
                else
                {
                    if (fileExists)
                    {
                        imageUrl = picture.FileName;
                    }
                    else
                    {
                        imageUrl = App.GetResourceUrl("/Resources/Picture.png");
                    }
                }
            }
            this.ImageUrl = imageUrl;
            this.HasErrors = !Validator.IsPictureValid(picture, account);
            this.PreviewTitleVisibility = (this.IsVideo ? Visibility.Visible : Visibility.Collapsed);
        }
    }
}